<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>单据管理</el-breadcrumb-item>
            <el-breadcrumb-item>报销单审批</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>单据列表</span>
            </div>
            <!-- 搜索区域 -->
            <el-input placeholder="请输入内容" v-model="queryInfo.searchContent" clearable
                      @clear="getTicketsList">
                <el-select v-model="queryInfo.select" slot="prepend" placeholder="请选择">
                    <el-option label="职工姓名" value="employee-name"></el-option>
                    <el-option label="工作部门" value="department"></el-option>
                </el-select>
                <el-button slot="append" icon="el-icon-search" @click="getTicketsList"></el-button>
            </el-input>
            <el-button class="addButton" type="primary" @click="showAddDialog">新增</el-button>
            <!-- 票据列表区域-->
            <el-table :data="ticketsList" border stripe
                      :header-cell-style="{'text-align':'center'}"
                      :cell-style="{'text-align':'center'}">
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="employeeName" label="职工姓名"></el-table-column>
                <el-table-column prop="department" label="职工部门" ></el-table-column>
                <el-table-column prop="sex" label="性别"></el-table-column>
                <el-table-column prop="age" label="年龄"></el-table-column>
                <el-table-column prop="fee" label="医疗费用"></el-table-column>
                <el-table-column prop="report" label="上报金额"></el-table-column>
                <el-table-column prop="date" label="上报日期" width="170px"></el-table-column>
                <el-table-column label="操作" width="150px">
                  <template slot-scope="scope">
                    <!--查看详情按钮-->
                    <el-tooltip class="item" effect="dark" content="查看详情" placement="top" :enterable="false">
                      <el-button type="primary" icon="el-icon-zoom-in" size="mini" @click="showCheckDialog(scope.row.receipt_id)"></el-button>
                    </el-tooltip>
                    <!--删除按钮-->
                    <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDeleteDialog(scope.row.receipt_id)"></el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :total="total"
                    :current-page="queryInfo.nowPage"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
        </el-card>
        <!-- 增加医疗表单的对话框 -->
        <el-dialog title="医疗表单" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-ruleForm">
              <el-form-item label="职工姓名" prop="employeeName">
                <el-input class="form-input" v-model="form.employeeName"></el-input>
              </el-form-item>
              <el-form-item label="职工工号" prop="workNumber">
                <el-input class="form-input" v-model="form.workNumber"></el-input>
              </el-form-item>
              <el-form-item label="职工部门" prop="department">
                <el-input class="form-input" v-model="form.department"></el-input>
              </el-form-item>
              <el-form-item label="就诊医院" prop="hospital">
                <el-input class="form-input" v-model="form.hospital"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                  <el-radio label="男"></el-radio>
                  <el-radio label="女"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="年龄" prop="age">
                <el-input class="form-input" type="age" v-model.number="form.age" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="医疗费用" prop="fee">
                <el-input class="form-input" type="number" v-model.number="form.fee" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="上报金额" prop="report">
                <el-input class="form-input" type="number" v-model.number="form.report" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="开票日期" prop="ticketDate">
                <el-date-picker
                  v-model="form.ticketDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-form>
            <!-- 单据图像区域 -->
            <el-upload
              ref="ticketPicture"
              class="upload-demo"
              drag
              action
              :http-request="handleUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              mutiple
              :limit="limit"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :list-type="listType"
              >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">{{tip}}</div>
            </el-upload>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="formSubmit('formRef')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 查看票据的对话框 -->
        <el-dialog title="票据详情" :visible.sync="checkDialogVisible" width="40%">
          <!-- 内容主体区域 -->
          <el-form :model="ticketInfoForm" label-width="100px" >
            <el-form-item label="职工姓名" prop="employeeName">
              <el-input class="form-input" v-model="ticketInfoForm.employeeName" disabled></el-input>
            </el-form-item>
            <el-form-item label="职工工号" prop="workNumber">
              <el-input class="form-input" v-model="ticketInfoForm.workNumber" disabled></el-input>
            </el-form-item>
            <el-form-item label="职工部门" prop="department">
              <el-input class="form-input" v-model="ticketInfoForm.department" disabled></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-input class="form-input" v-model="ticketInfoForm.sex" disabled></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input class="form-input" type="age" v-model.number="ticketInfoForm.age" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="就诊医院" prop="hospital">
              <el-input class="form-input" v-model="ticketInfoForm.hospital" disabled></el-input>
            </el-form-item>
            <el-form-item label="医疗费用" prop="fee">
              <el-input class="form-input" type="number" v-model.number="ticketInfoForm.fee" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="上报金额" prop="report">
              <el-input class="form-input" type="number" v-model.number="ticketInfoForm.report" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="开票日期" prop="ticketDate">
              <el-input class="form-input" type="date" v-model="ticketInfoForm.ticketDate" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="上报日期" prop="date">
              <el-input class="form-input" type="date" v-model="ticketInfoForm.date" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="票据原始影像" prop="picture">
              <el-image
                style="width: 300px; height: 200px ;display: block"
                :src="ticketInfoForm.picture"
                :preview-src-list="srcList">
              </el-image>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!-- 删除票据的对话框 -->
        <el-dialog title="提示" :visible.sync="deleteDialogVisible"
                   width="30%" >
          <!-- 内容主体区域 -->
          <span>确定删除该条票据吗?</span>
          <!-- 底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteTicket">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
import {BosClient} from "@baiducloud/sdk"

  //将查询数据JSON化
  const qs=require('querystring')
  export default {
    //子组件接收父组件传递的属性,用于上传图片
    props: {
      tip: {
        type: String,
        default: '上传大小不能超过10M'
      },
      limit: {
        type: Number,
        default: 1
      },
      action: {
        type: String,
        default: ''
      },
      headers: {
        type: Object,
        default: () => {}
      },
      name: {
        type: String,
        default: ''
      },
      listType: {
        type: String,
        default: 'picture'
      }
    },
    data() {
      return {
        //票据列表
        ticketsList: [],
        // 总数
        total: 0,
        //查询列表参数信息
        queryInfo: {
          //当前页数
          nowPage: 1,
          //当前每页显示多少条数据
          pageSize: 10,
          // 选择种类
          select: '',
          //搜索内容
          searchContent: '',
          //审核进程
          process: 0
        },
        // 控制新增票据对话框的显示与隐藏
        addDialogVisible: false,
        // 控制查看票据对话框的显示与隐藏
        checkDialogVisible: false,
        // 控制删除票据对话框的显示与隐藏
        deleteDialogVisible: false,
        //操作的表格对象id
        idInfo: {
          receipt_id: 1
        },
        //表单内容
        form: {
          employeeName: '',
          workNumber: '',
          department: '',
          sex: '',
          age: '',
          hospital: '',
          fee: '',
          report: '',
          ticketDate: null
        },
        //表单验证规则
        rules: {
          employeeName: [
            { required: true, message: '请输入职工姓名', trigger: 'blur' }
          ],
          workNumber: [
            { required: true, message: '请填写职工工号', trigger: 'blur' }
          ],
          department: [
            { required: true, message: '请输入职工部门', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          age: [
            { required: true, message: '请填写年龄', trigger: 'blur' },
            { type:'number',message: '年龄必须为数字',trigger: 'blur'}
          ],
          hospital: [
            { required: true, message: '请填写医院', trigger: 'blur' }
          ],
          fee: [
            { required: true, message: '请填写医疗费用', trigger: 'blur' },
            { type:'number',message: '医疗费用必须为数字',trigger: 'blur'}
          ],
          report: [
            { required: true, message: '请填写上报金额', trigger: 'blur' },
            { type:'number',message: '上报金额必须为数字',trigger: 'blur'}
          ]
        },
        //票据详情
        ticketInfoForm: {},
        //图片预览功能
        srcList: [],
        //图片列表
        fileList: [],
        //图片内容
        file: null
      }
    },
    created () {
      this.getTicketsList()
      const config = {
        credentials: {
          ak: "79c9cba51f0a4df1a6281aab51cdad3e",//AccessKey
          sk: "b21aa6a38adf439fa2dd26c6033e1311" //SecretKey
        },
        endpoint: "http://bj.bcebos.com"
      };
      this.client = new BosClient(config)
    },
    methods: {

      /**
       * 获取全部未审核的列表
       */
      async getTicketsList () {
        let res=await this.$http.get('unchecked-ticket', { params: this.queryInfo })
        if (res.status !== 200) {
          if(res.status === 403) {
            return this.$message.error('您没有获取审核列表的权限!')
          }
          return this.$message.error('获取审核列表失败!')
        }
        this.total = res.data.total
        this.ticketsList = res.data.tickets
      },

      /**
       * 监听分页尺寸改变
       * @param newSize:新的分页尺寸
       */
      handleSizeChange(newSize) {
        this.queryInfo.pageSize=newSize
        this.getTicketsList()
      },

      /**
       * 监听当前页码变化
       * @param nowPage:当前页码
       */
      handleCurrentChange(nowPage){
        this.queryInfo.nowPage=nowPage
        this.getTicketsList()
      },

      /**
       * 展示添加票据的对话框
       */
      showAddDialog() {
        this.addDialogVisible=true;
      },

      /**
       * 关闭添加票据对话框之后的重置
       */
      addDialogClosed(){
        this.$refs.formRef.resetFields();
        this.$refs.ticketPicture.clearFiles();
      },

      /**
       * 提交票据表单
       * @param formName:票据引用名
       */
      formSubmit(formName){
        const uuid=this.guid();
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const reader = new FileReader();
            reader.readAsArrayBuffer(this.file);
            reader.onload = () => {
              this.client.putObject("tickets", uuid+".jpeg", new Buffer(reader.result)
              ).then(
                res => console.log(res)
              ).catch(() => {
                this.$message({
                  type: 'info',
                  message: '图片上传失败'
                })
                return false
              })
            };
            this.addTicket(uuid);
          } else {
            return this.$message.error('表单信息不合法!')
          }
        });
      },

      /**
       * 向后台发起添加票据请求
       */
      async addTicket (uuid){
        this.form.picture=uuid+".jpeg"
        let res=await this.$http.post('addticket',this.form)
        if(res.status!==200){
          if(res.status === 403) {
            return this.$message.error('您没有添加表单的权限!')
          }
          return this.$message.error('添加表单失败!')
        }
        else{
          this.addDialogVisible=false
          this.$message.success("添加成功")
          this.getTicketsList()
        }
      },

      /**
       * 设置票据图片的url
       */
      setImageUrl:function(pictureUrl){
        // 0. 设置请求参数
        const method = 'GET'
        const Host = 'tickets.bj.bcebos.com';
        const accessKey = '79c9cba51f0a4df1a6281aab51cdad3e';
        const secretKey = 'b21aa6a38adf439fa2dd26c6033e1311';
        let url='/'+pictureUrl; // 要有 "/"
        const params = {};
        const headers = {
          'Host': Host
        };
        // 1. 生成认证字符串signature
        const Auth = require('@baiducloud/sdk').Auth;
        const auth = new Auth(accessKey, secretKey);
        let signature = auth.generateAuthorization(method, url, params, headers);

        // 2. API方式 访问资源
        let picture = 'http://' + Host + url + '?authorization=' + signature;
        // console.log(picture)
        return picture
      },

      /**
       * 展示查看票据的对话框
       * @param id 票据ID
       */
      async showCheckDialog(id){
        this.idInfo.receipt_id=id
        // console.log(this.idInfo.receipt_id)
        let res=await this.$http.get('ticket', { params: this.idInfo })
        //console.log(res)
        if (res.status !== 200) {
          if(res.status === 403) {
            return this.$message.error('您没有获取票据详情的权限!')
          }
          return this.$message.error('获取票据详情失败!')
        }
        this.ticketInfoForm=res.data
        let temp=this.ticketInfoForm.picture
        this.ticketInfoForm.picture = this.setImageUrl(temp)
        this.srcList.push(this.ticketInfoForm.picture)
        this.checkDialogVisible = true
      },

      /**
       * 展示删除票据的对话框
       */
      showDeleteDialog(id){
        this.idInfo.receipt_id=id
        this.deleteDialogVisible = true
      },

      /**
       * 删除票据的方法
       */
      async deleteTicket() {
        let res=await this.$http.delete('ticket', { params: this.idInfo })
        if (res.status !== 200) {
          if(res.status === 403) {
            return this.$message.error('您没有删除票据的权限!')
          }
          return this.$message.error('删除失败!')
        }else {
          this.$message.success("删除成功")
        }
        //console.log(this.idInfo.receipt_id)
        this.getTicketsList()
        this.deleteDialogVisible = false
      },

      /**
       * 文件列表移除的方法
       * @param file 移除的图片名
       * @param fileList 图片列表
       */
      handleRemove(file, fileList) {
        // console.log(file, fileList);
      },

      /**
       * 预览图片
       * @param file 要预览的图片名
       */
      handlePreview(file) {
        this.$emit('on-preview', file)
      },

      /**
       * 文件超出个数时的限制函数
       * @param files
       * @param fileList
       */
      handleExceed(files, fileList) {
        this.$message.warning(`每次只能上传 ${this.limit} 张图片`)
      },

      /**
       * 删除文件之前的钩子函数
       * @param file
       * @param fileList
       * @returns {Promise<MessageBoxData> | *}
       */
      beforeRemove(file, fileList) {
        // this.$emit('before-remove', file, fileList)
        // return this.$confirm(`确定移除 ${file.name}？`)
        return this.$confirm(`确定移除 ${file.name}？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        // }).then(() => {
        //   this.$message({
        //     type: 'success',
        //     message: '移除成功!'
        //   });
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已取消移除'
        //   });
        });
      },

      /**
       * 处理上传的函数
       * @param option 上传的文件
       */
      handleUpload(option) {
        this.file=option.file
      },

      /**
       * 生成uuid的函数
       * @returns {string}
       */
      guid:function() {
        function S4() {
          return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
      }
    }
  }
</script>
<style lang="less" scoped>
    .el-input {
        width: 500px;
    }
    .el-select {
        width: 110px;
    }
    .input-with-select .el-input-group__prepend {
        background-color: #fff;
    }
    .el-table {
        margin-top: 15px;
        font-size: 12px;
    }
    .el-pagination {
        margin-top: 15px;
    }
    .addButton {
        margin-left: 20px;
    }
    .form-input {
      width: 80%;
    }
    .upload-demo {
      width: 70%;
      margin: 0 auto;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .el-icon-upload {
      width: 40%;
    }
    .el-upload__text {
      margin: 0 auto;
      width: 60%;
    }
    .el-upload__tip {
      width: 60%;
    }
</style>
